/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.dataprovider.view.suite;

import com.compomics.dataprovider.control.logic.fasta.FastaSourceConverter;
import com.compomics.dataprovider.control.logic.fasta.UniprotFastaProvider;
import com.compomics.dataprovider.control.logic.storage.FastaManager;
import com.compomics.dataprovider.model.fasta.FastaStream;
import com.compomics.dataprovider.view.suite.model.FastaRepositoryProperties;
import com.compomics.dataprovider.view.suite.panels.filetree.FileTreeSelectionListener;
import com.compomics.dataprovider.view.suite.panels.importing.FastaFileChooser;
import com.compomics.dataprovider.view.taxonomy.TaxonomyTreeDialog;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Kenneth
 */
public class FastaProviderSuite extends javax.swing.JFrame {

    private static FastaProviderSuite suite;
    File repository = new File(FastaRepositoryProperties.getRepositoryPath());
    FastaManager manager = new FastaManager(repository);

    /**
     * Creates new form FastaProviderSuite
     *
     * @return the parent frame instance
     * @throws java.io.IOException
     */
    public static FastaProviderSuite getInstance() throws IOException {
        if (suite == null) {
            suite = new FastaProviderSuite();
        }
        return suite;
    }

    private FastaProviderSuite() throws IOException {
        initComponents();
        init();
        repository.mkdirs();
        fastaFileTree.updateTree(repository);
    }

    private void init() {
        fastaFileTree.addTreeSelectionListener(new FileTreeSelectionListener(fastaFileTable));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        fastaFileTree = new com.compomics.dataprovider.view.suite.panels.filetree.FastaFileTree();
        jScrollPane1 = new javax.swing.JScrollPane();
        fastaFileTable = new com.compomics.dataprovider.view.suite.panels.filetable.FastaFileTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        fileTable2 = new com.compomics.dataprovider.view.suite.panels.filetable.FastaFileTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Fasta Management Software");
        setBackground(new java.awt.Color(255, 255, 255));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jScrollPane2.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane2.setViewportView(fastaFileTree);

        fastaFileTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Name", "Size (MB)", "Last Modified"
            }
        ));
        jScrollPane1.setViewportView(fastaFileTable);

        fileTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Name", "Size (MB)", "Last Modified"
            }
        ));
        jScrollPane4.setViewportView(fileTable2);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jScrollPane1, jScrollPane2});

        jMenuBar1.setBackground(new java.awt.Color(255, 255, 255));

        jMenu1.setText("File");

        jMenu3.setText("Import");

        jMenuItem5.setText("From fasta");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem5);

        jMenuItem4.setText("From UniPro");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem4);

        jMenuItem1.setText("From URL");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem1);

        jMenu1.add(jMenu3);

        jMenuItem2.setText("Exit");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        FastaFileChooser chooser = new FastaFileChooser();
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                chooser.importFiles(fastaFileTree.getSelectedFolder());
                fastaFileTree.updateTree(repository);
            } catch (IOException ex) {
                Logger.getLogger(FastaProviderSuite.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        TaxonomyTreeDialog dialog = new TaxonomyTreeDialog(null, true);
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);

        dialog.isReviewOnly();

        for (Map.Entry<String, String> anOrganismEntry : dialog.getSelectedTaxonomyEntries().entrySet()) {
            String anOrganism = anOrganismEntry.getValue();
            String anOganismID = anOrganismEntry.getKey();
            File selectedFolder = fastaFileTree.getSelectedFolder();
            if (selectedFolder.equals(new File(FastaRepositoryProperties.getRepositoryPath()))) {
                selectedFolder = new File(selectedFolder, anOrganism);
            }
            File fastaFile = new File(selectedFolder, anOrganism + ".fasta");
            if (fastaFile.exists()) {
                //show dialog to ask for override   
            } else {
                fastaFile.getParentFile().mkdirs();
                try {
                    fastaFile.createNewFile();
                } catch (IOException ex) {
                    System.out.println("Could not create new file !");
                }
            }
            try {
                FastaStream stream = new FastaStream(FastaSourceConverter.convertToStream(fastaFile));
                FastaStream downloadFastaToStream = UniprotFastaProvider.downloadFastaToStream(stream, anOrganism.replace("+", " "), anOganismID, dialog.isReviewOnly());
                downloadFastaToStream.save(fastaFile, true);
            } catch (Exception ex) {
                System.out.println("Could not find " + anOrganism + " : ");
                ex.printStackTrace();
            }
        }
        fastaFileTree.updateTree(repository);
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        File selectedFolder = fastaFileTree.getSelectedFolder();
        File fastaFile;
        JTextField URLField = new JTextField();

        Object[] message = {
            "URL:", URLField,};
        int option = JOptionPane.showConfirmDialog(null, message, "Import", JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.OK_OPTION) {
            URL url;
            try {
                url = new URL(URLField.getText());
                String baseName = FilenameUtils.getBaseName(url.toExternalForm());
                if (selectedFolder.equals(new File(FastaRepositoryProperties.getRepositoryPath()))) {
                    selectedFolder = new File(selectedFolder, baseName);
                }
                fastaFile = new File(selectedFolder, baseName + ".fasta");
                fastaFile.getParentFile().mkdirs();
                fastaFile.createNewFile();
                FastaStream stream = new FastaStream(FastaSourceConverter.convertToStream(fastaFile));
                stream.concatenate(url);
                stream.save(fastaFile, true);
            } catch (MalformedURLException ex) {
                Logger.getLogger(FastaProviderSuite.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException | NullPointerException ex) {
                Logger.getLogger(FastaProviderSuite.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        reload();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FastaProviderSuite.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FastaProviderSuite.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FastaProviderSuite.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FastaProviderSuite.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    FastaProviderSuite fastaProviderSuite = FastaProviderSuite.getInstance();
                    fastaProviderSuite.setLocationRelativeTo(null);
                    fastaProviderSuite.setVisible(true);

                } catch (IOException ex) {
                    Logger.getLogger(FastaProviderSuite.class
                            .getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.compomics.dataprovider.view.suite.panels.filetable.FastaFileTable fastaFileTable;
    private com.compomics.dataprovider.view.suite.panels.filetree.FastaFileTree fastaFileTree;
    private com.compomics.dataprovider.view.suite.panels.filetable.FastaFileTable fileTable2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    // End of variables declaration//GEN-END:variables

    public void reload() {
        fastaFileTree.updateTree(repository);
        fastaFileTable.reset();
    }
}
